<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.SQLException" %><%--
  Created by IntelliJ IDEA.
  User: cc
  Date: 2020/10/21
  Time: 9:18
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<jsp:useBean id="user" class="com.media.bean.UserBean"></jsp:useBean>
<jsp:setProperty name ="user" property="*"></jsp:setProperty>
<%
        //加载数据库驱动
        Class.forName("com.mysql.jdbc.Driver");

        //建立数据库连接
        String url ="jdbc:mysql://localhost：3306/book";//数据库连接地址
        Connection connection = DriverManager.getConnection(url,"root","root");
        //第一个root为数据库的用户  第二个root为数据库的密码

        connection.setAutoCommit(false);
        //关闭自动提交

        String sqL ="insert into user (username,password,gender,age) value (?,?,?,?)";
        //在 PreparedStatement 中使用问好代替实际参数

        PreparedStatement ps = connection.prepareStatement(sqL);

        ps.setString(1,user.getUsername());
        ps.setString(2,user.getPassword());
        ps.setInt(3,user.getGender());
        ps.setInt(4,user.getAge());
        ps.setInt(5,0);

        ps.addBatch();//添加到批处理

        ps.setString(1,user.getUsername()+"111");
        ps.setString(2,user.getPassword()+"111");
        ps.setInt(3,user.getGender());
        ps.setInt(4,user.getAge());
        ps.setInt(5,0);

        ps.addBatch();
        //添加到批处理 insert update delete

        int[] count={0};

        try{
                count=ps.executeBatch();
                connection.commit();//手动提交
        }catch (SQLException e){
                connection.rollback();//回滚操作
                e.printStackTrace();
        }

        ///int count=ps.executeUpdate();

        if (count[0]>0){
            out.print("添加成功");
        }else{
            out.print("添加失败");
        }
        response.setHeader("refresh","3;url=home.jsp");

        //事务

        //mysql 数据库引擎 MyISAM不支持事务
        //默认Innodb 支持事务
%>